//
//  OneHeroViewController.m
//  LOL视频播放
//
//  Created by 花花蔡 on 2016/12/14.
//  Copyright © 2016年 com.HuaHuaCai. All rights reserved.
//

#import "OneHeroViewController.h"
#import "URL.h"
#import "Public.h"
#import "VideoPlayViewController.h"
#import "VideoModel.h"
#import "NetWorkingTool.h"
#import <MJRefresh.h>
#import <MJExtension.h>
#import "VideoTableViewCell.h"
#import "CoreDataManager.h"
@interface OneHeroViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) NSMutableArray *dataArray;


@end

@implementation OneHeroViewController {
    int times;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = self.cName;
    times = 1;
    [self loadMoreData];
    [self.view addSubview:self.tableView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 加载数据
- (void)loadMoreData {
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        NSString *time = [NSString stringWithFormat:@"%d",times];
        NSString *urlStr = [NSString stringWithFormat:@"%@%@%@%@%@",VideoURL_1,self.heroId,VideoURL_2,time,VideoURL_3];
        
        [[NetWorkingTool sharedTools] requestMethod:GET WithURL:urlStr parameters:nil callBack:^(id data, NSError *error) {
            if (error) {
                [self.tableView.mj_header endRefreshing];
                NSLog(@"%@",error);
            }
            NSDictionary *Data = data[@"Data"];
            NSArray *Result = Data[@"Result"];
            _dataArray = [VideoModel mj_objectArrayWithKeyValuesArray:Result];
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
        }];
    }];
    [self.tableView.mj_header beginRefreshing];
    
    //上拉加载更多
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        times += 1;
        NSString *time = [NSString stringWithFormat:@"%d",times];
        NSString *urlStr = [NSString stringWithFormat:@"%@%@%@%@%@",VideoURL_1, self.heroId, VideoURL_2, time, VideoURL_3];
        //开辟一个串行队列
        dispatch_queue_t queue = dispatch_get_main_queue();
        
        //异步执行
        dispatch_async(queue, ^{
            
            [[NetWorkingTool sharedTools] requestMethod:GET WithURL:urlStr parameters:nil callBack:^(id data, NSError *error) {
                if (error) {
                    [self.tableView.mj_footer endRefreshing];
                }
                NSDictionary *Data = data[@"Data"];
                NSArray *Result = Data[@"Result"];
                NSArray *videoArray = [VideoModel mj_objectArrayWithKeyValuesArray:Result];
                for (VideoModel *obj in videoArray) {
                    [_dataArray addObject:obj];
                }
                [self.tableView reloadData];
                [self.tableView.mj_footer endRefreshing];
                
                //如果没有更多数据了,把上拉加载更多隐藏
                if (videoArray.count == 0) {
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        self.tableView.mj_footer.hidden = YES;
                    });
                }
            }];
            
        });
    }];
    
}

#pragma mark - tableView 代理方法


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    VideoTableViewCell *cell = [VideoTableViewCell loadCellWithTableView:tableView];
    cell.model = _dataArray[indexPath.row];
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    VideoModel *model = _dataArray[indexPath.row];
    NSDictionary *dict = [[NSDictionary alloc] init];
    //找到Model.F中三种播放格式的第一种(超清，MP4，标清),即超清
    for (dict in model.F) {
        break;
    }
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@%@%@",PlayURL_1, model.I,PlayURL_2,dict[@"Key"]];
    
    [[NetWorkingTool sharedTools] requestMethod:GET WithURL:urlString parameters:nil callBack:^(id data, NSError *error) {
        
        NSArray *Data = data[@"Data"];
        NSDictionary *dict = [[NSDictionary alloc] init];
        
        VideoPlayViewController *player = [[VideoPlayViewController alloc] init];
        
        for (dict in Data) {
            player.urlStr = dict[@"Url"];
            break;
        }
        [self presentViewController:player animated:YES completion:nil];
        
        //数据存入数据库
        BOOL isSave = [[CoreDataManager manager] addDataWithPictureName:model.P Title:model.T Date:model.A Count:model.V VideoURStr:player.urlStr];
        
        if (isSave) {
            NSLog(@"保存成功");
        }else
            NSLog(@"保存失败");
        
    }];
    
    
    //    //将模型转换为字典
    //    NSMutableDictionary *modelDic = [model mj_keyValues];
    //    NSLog(@"%@",modelDic);
}

#pragma mark - 懒加载
-(UITableView *)tableView {
    
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, screen_width, screen_height) style:UITableViewStylePlain];
        //自动适配保证左右上下边距不变
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.rowHeight = 110 * KWidth_ScaleW;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        _tableView.separatorInset = UIEdgeInsetsMake(0, 5, 0, 5);
        
    }
    return _tableView;
}

@end
